<?php
class UtilD {
	public static function toHtml($url) {
		/*$url = trim($url);
		//if(strpos($url,'?') === 0){ 
           // $url = '/'.$url;
		//}
		//只有前台用户才进行静态化
		if(Yii::app()->controller->userType == '2'){
		    $lurl = strtolower($url);
		    //域名处理
			$domain = '';
			if(Yii::app()->params['isDomain']){
			    $domain = DomainD::getInstance()->getDomain($lurl);
			}

		    if(isset(Yii::app()->params['isStatic']) && Yii::app()->params['isStatic']){
		        $staticObj = Yii::app()->controller->getStaticInstance();
			    if($staticObj){
				    $lurl = strtolower($url);
		            $routeConfig = $staticObj->getRouteConfigFromDynamicUrl($lurl);
				    //$routeConfig = $staticObj->getRouteConfigFromDynamicUrl('?r=www/Activity/index');
				    //var_dump($routeConfig);
		            if($routeConfig && $routeConfig['sta']){
                        $url = $staticObj->genStaticUrl($lurl);
		            }
			    }
		    }

            if(strpos($url,'?') === 0){ 
                $url = '/'.$url;
		    }
			//echo $domain.'huitest1';
			if($domain){
                $url = $domain . $url;
			}
		}
		return $url;*/
		$url = trim($url);
		if(Yii::app()->controller->userType == '2')
		{
		    $lurl = strtolower($url);
		    //域名处理
			$domain = '';
			if(Yii::app()->params['isDomain']){
			    $domain = DomainD::getInstance()->getDomain($lurl);
			}

            if(isset(Yii::app()->params['isStatic']) && Yii::app()->params['isStatic'])
			{
                $staticD = StaticFactoryD::getStaticD();
		       /* $querystring = parse_url($url,PHP_URL_QUERY);
                parse_str($querystring,$querys);
				$route = isset($querys['r'])?$querys['r']:'';
				StaticFactoryD::setStaticUrlHandlerStyle($staticD,$route);*/
				$url = $staticD->genStaticUrl($url);
			}

		    if(strpos($url,'http://') !== 0 && strpos($url,'/') !== 0)
		    {
                $url = '/'.$url;
		    }

			if($domain){
                $url = $domain . $url;
			}
		}
  
		return $url;
	}
	/**
	 * 权限判断，当前用户是否有执行某任务的权限
	 * @param string $route
	 * @return boolean
	 */
	public static function isPass($route){
		if(Yii::app()->admin->isGuest){
			return false;
		}
		//判断权限路由，检查是否要例外，如admin/article/index&pkey=help，检查更细的权限
		$pkey=Yii::app()->request->getParam('pkey');
		!is_null($pkey) && $route.='&pkey=' . $pkey;
		if(in_array($route, array_keys(Yii::app()->params['allowedTask']))){
			return true;
		}
        $route = strtolower($route);
		$task=Admin::getMemTask($route);
		if(is_null($task))
			return false;
		if($task['sta']!=1)
			return false;
		$task_id=$task['id'];
		$permission=Admin::getCurrentUserPermission();
		if(in_array($task_id, $permission)){
			return true;
		}else{
			return false;
		}
	}

	/**
	格式化消息
	 **/
	public static function handleResult($code, $result) {
		return CJSON::encode ( array ('key' => $code, 'keyMain' => $result ) );
	}
	/**
	 * 
	 * @param string $result
	 * @throws Exception
	 * @return array
	 */
	public static function parseResult($result) {
		$arr = CJSON::decode ( trim ( $result ) );
		if (is_null ( $arr ) || ! is_array ( $arr ) || ! isset ( $arr ['key'] ) || (! isset ( $arr ['keyMain'] ) && !is_null($arr ['keyMain']))) {
            throw new Exception (__CLASS__ . "=>" . __LINE__ .  "异常错误:" . $result );
		}
		return $arr;
	}
	/**
	 * 获取格式化的日期
	 * @param int $time	unix时间戳
	 * @param string $default 默认显示，当时间没有设定时
	 */
	public static function getDate($time, $default = '') {
		$time=UtilD::deSlashes($time);
		if (is_int ( $time )) {
			$t = date ( 'Y-m-d', $time );
			if ($t != '1970-01-01') {
				return $t;
			}
		}
		return $default;
	}
	/**
	 * 获取格式化的年份
	 * @param int $time
	 * @param string $default
	 */
	public static function getYear($time, $default = '') {
		$time=UtilD::deSlashes($time);
		if (is_int ( $time )) {
			$t = date ( 'Y', $time );
			if ($t != '1970') {
				return $t;
			}
		}
		return $default;
	}
	/**
	 * 获取格式化的日期时间
	 * @param int $time	unix时间戳
	 * @param string $default 默认显示，当时间没有设定时
	 */
	public static function getDatetime($time, $default = '') {
		$time=UtilD::deSlashes($time);
		if (is_int ( $time )) {
			$t = date ( 'Y-m-d H:i:s', $time );
			if ($t != '1970-01-01 08:00:00') {
				return $t;
			}
		}
		return $default;
	}
	
	/**
	 * 获取相应格式时间
	 * @param string $rule	时间格式
	 * @param int $time	unix时间戳
	 * @param string $default 默认显示，当时间没有设定时
	 */
	public static function getNewDatetime($rule='Y-m-d',$time, $default = '') {
		$time=UtilD::deSlashes($time);
		if (is_int ( $time )) {
			$t = date ($rule, $time );
			return $t;
		}
		return $default;
	}
	/**
	 * 处理时间，按照人为习惯显示
	 * 
	 * @param $time int       	
	 * @return string
	 */
	public static function parseTime($time = 0) {
		$now = time ();
		$diff = $now - $time;
		if ($diff < 60) {
			$msg = '刚刚';
		} else if ($diff < 3600) {
			$msg = ceil ( $diff / 60 ) . '分钟前';
		} else if ($diff < 86400) { // 一天
			$msg = ceil ( $diff / 3600 ) . '小时前';
		} else {
			$msg = date ( 'm.d', $time );
		}
		return $msg;
	}
	
	public static function parseTimeCn($time = 0) {
		$now = time ();
		$diff = $now - $time;
		if ($diff < 60) {
			$msg = '刚刚';
		} else if ($diff < 3600) {
			$msg = ceil ( $diff / 60 ) . '分钟前';
		} else if ($diff < 86400) { // 一天
			$msg = ceil ( $diff / 3600 ) . '小时前';
		} else {
			$msg = '一天前';//date ( 'm月d日', $time );
		}
		return $msg;
	}
	/**
	 * 中文字符串截取
	 * @param string    $string  需要截取的字符串
	 * @param int       $length  截取的长度
	 * @param string    $etc     被截取的部分替换的字符串
	 * @param bool    $encry     是否需要返回转义后的字符串
	 */
	public static function cutString($string, $length, $etc = '...', $charset = 'UTF-8' ,$encry = true) {
		//$string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, $charset );
        /*
		$string=  UtilD::deSlashes($string);
		$strlen = mb_strlen ( $string, $charset );
		if ($length >= $strlen) {
			if($encry){
                $string = UtilD::enSlashes($string);
				//strpos($string,'&amp;nbsp;')!==false && $string = str_replace('&amp;nbsp;','&nbsp;',$string);
			}
		} else {
			strpos($string,'&nbsp;')!==false && $string = str_replace('&nbsp;',' ',$string);
			$string = mb_substr ( $string, 0, $length, $charset );
			strpos($string,' ')!==false && $string = str_replace(' ','&nbsp;',$string);
			if($encry){
                $string = UtilD::enSlashes($string);		
			}
			strpos($string,'&#38;nbsp&#59;')!==false && $string = str_replace('&#38;nbsp&#59;','&nbsp;',$string);
			$string .= $etc;
		}
		return $string;
		*/
		$string=  UtilD::deSlashes($string);
		$trans=array('&#38;nbsp&#59;'=>' ', '&nbsp;'=>' ');
		$string=strtr($string, $trans);
		$string = trim(strip_tags($string));
		$string=mb_strimwidth($string, 0, $length*2, $etc, $charset);
		strpos($string,' ')!==false && $string = str_replace(' ','&nbsp;',$string);
		if($encry){
        	$string = UtilD::enSlashes($string);		
		}
		strpos($string,'&#38;nbsp&#59;')!==false && $string = str_replace('&#38;nbsp&#59;','&nbsp;',$string);
		return $string;
	}
	protected static function clearEmpty(array $arr) {
		if (! function_exists ( 'ept' )) {
			function ept($var) {
				if (is_string ( $var )) {
					$var = trim ( $var );
				}
				if ($var === false || $var === '0' || $var === 0) {
					return true;
				}
				return ! empty ( $var );
			}
		}
		return (array_filter ( $arr, "ept" ));
	}
	protected static function clearNull(array $arr) {
		if (! function_exists ( 'nul' )) {
			function nul($var) {
				$flag = $var !== null;
				return ($flag);
			}
		}
		return (array_filter ( $arr, "nul" ));
	}
	/**
	去除一组数组中的空元素
	 **/
	public static function clearNullOrEmptyValue(array &$array) {
		$array = self::clearEmpty ( $array );
		return $array;
	}
	public static function clearNullValue(array &$array) {
		$array = self::clearNull ( $array );
	}
    /**
     * 数据转换成有[&#]
     */
	public static function enSlashes($value, $ucfirst = false) {
		if (empty ( $value )) {
			return $value;
		}
		//过滤不完整的utf8字符
		if(mb_check_encoding($value,'GBK') !== true){
			$value=self::filterPartialUTF8Char($value);
		}
        if(mb_check_encoding($value,'GBK') == false && mb_check_encoding($value,'UTF-8') == false){
            return '';
        }
        if (mb_check_encoding($value,'GBK') == true && mb_check_encoding($value,'UTF-8')!==true){
            $value = mb_convert_encoding($value, 'UTF-8', 'GBK');            
        }
		if(strpos($value,'&')!==false){
			$value =htmlspecialchars_decode($value, ENT_QUOTES|ENT_NOQUOTES);
		}
		$filters = array ('&' => '&#' . ord ( '&' ) . ';', '#' => '&#' . ord ( '#' ) . ';', ' ' => '&#' . ord ( ' ' ) . ';', '\'' => '&#' . ord ( '\'' ) . ';', '>' => '&#' . ord ( '>' ) . ';', 
				'<' => '&#' . ord ( '<' ) . ';', '=' => '&#' . ord ( '=' ) . ';', '!' => '&#' . ord ( '!' ) . ';', '^' => '&#' . ord ( '^' ) . ';', '+' => '&#' . ord ( '+' ) . ';', 
				'-' => '&#' . ord ( '-' ) . ';', '*' => '&#' . ord ( '*' ) . ';', '/' => '&#' . ord ( '/' ) . ';', '%' => '&#' . ord ( '%' ) . ';', '|' => '&#' . ord ( '|' ) . ';', 
				'~' => '&#' . ord ( '~' ) . ';', '@' => '&#' . ord ( '@' ) . ';','"' => '&#' . ord ( '"' ) . ';',';' => '&#' . ord ( ';' ) . ';' );
		$value = strtr ( $value, $filters );
		if(strpos($value,'&#38;&#35;')!==false){//如果本身就含转义字符
			$value=str_replace('&#38;&#35;','&#',$value);
		}
		if ($ucfirst === true) {
			$value = strtolower ( $value );
		}
		return $value;
	
	}
    /**
     * 有[&#]的数据转换成正常数据
     */
	public static function deSlashes($value, $ucfirst = false) {
		if (empty ( $value )) {
			return $value;
		}
		if(mb_check_encoding($value,'GBK') !== true){
			$value=self::filterPartialUTF8Char($value);
		}
        if(mb_check_encoding($value,'GBK') == false && mb_check_encoding($value,'UTF-8') == false){
            return '';
        }
        if (mb_check_encoding($value,'GBK') == true && mb_check_encoding($value,'UTF-8')!==true){
            $value = mb_convert_encoding($value, 'UTF-8', 'GBK');            
        }
		if(strpos($value,'&')!==false){
			$value =htmlspecialchars_decode($value, ENT_QUOTES|ENT_NOQUOTES);
		}
		if(strpos($value,'&#')===false){
			return $value;
		}

		$filters = array ('&' => '&#' . ord ( '&' ) . ';', '#' => '&#' . ord ( '#' ) . ';', ' ' => '&#' . ord ( ' ' ) . ';', '\'' => '&#' . ord ( '\'' ) . ';', '>' => '&#' . ord ( '>' ) . ';', 
				'<' => '&#' . ord ( '<' ) . ';', '=' => '&#' . ord ( '=' ) . ';', '!' => '&#' . ord ( '!' ) . ';', '^' => '&#' . ord ( '^' ) . ';', '+' => '&#' . ord ( '+' ) . ';', 
				'-' => '&#' . ord ( '-' ) . ';', '*' => '&#' . ord ( '*' ) . ';', '/' => '&#' . ord ( '/' ) . ';', '%' => '&#' . ord ( '%' ) . ';', '|' => '&#' . ord ( '|' ) . ';', 
				'~' => '&#' . ord ( '~' ) . ';', '@' => '&#' . ord ( '@' ) . ';','"' => '&#' . ord ( '"' ) . ';',';' => '&#' . ord ( ';' ) . ';' );
		$value = strtr ( $value, array_flip ( $filters ) );
		if ($ucfirst === true) {
			$value = strtolower ( $value );
		}
		return $value;
	
	}
	//支持到四维数组
	public static function enSlashesAll(&$data, $ucfirst = false) {
		foreach ( $data as $key => $value ) {
			if (is_array ( $value )) {
				foreach ( $value as $kkk => $vvv ) {
					if (is_array ( $vvv )) {
						foreach ( $vvv as $kk => $vv ) {
							if (is_array ( $vv )) {
								foreach ( $vv as $k => $v ) {
									if (is_array ( $v )) {
										throw new CHttpException ( 403, '不正确的请求' );
									} else {
										$data [$key] [$kkk] [$kk] [$k] = self::enSlashes ( trim($v), $ucfirst );
									}
								}
							} else {
								$data [$key] [$kkk] [$kk] = self::enSlashes ( trim($vv), $ucfirst );
							}
						}
					} else {
						$data [$key] [$kkk] = self::enSlashes ( trim($vvv), $ucfirst );
					}
				}
			} else {
				$data [$key] = self::enSlashes ( trim($value), $ucfirst );
			}
		}
		return $data;
	}
	//判断ipv4地址是否是一个局域网地址
	public static function isInternalp($ip) { 
		$ip = ip2long($ip); 
		$net_a = ip2long('10.255.255.255') >> 24; //A类网预留ip的网络地址 
		$net_b = ip2long('172.31.255.255') >> 20; //B类网预留ip的网络地址 
		$net_c = ip2long('192.168.255.255') >> 16; //C类网预留ip的网络地址 
		return $ip >> 24 === $net_a || $ip >> 20 === $net_b || $ip >> 16 === $net_c; 
}
	/**
	根据用户ip获得地区 只精确到地级市
	反回一个二位数组
	 **/
	public static function getAreaByIP($ip) {
		try {
			$qqwry = new qqwry ( '/home/www/qqwry.dat' );
			$area = $qqwry->q ( $ip );
			if (is_array ( $area ) && count ( $area )) {
				if (! empty ( $area [0] )) {
					$ischina = false;
					$area [0] = mb_convert_encoding($area [0],'UTF-8','GBK');
                    $area [1] = mb_convert_encoding($area [1],'UTF-8','GBK');
					if (strpos ( $area [0], '广西' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '广西', '广西,', $area [0] );
					}elseif (strpos ( $area [0], '新疆' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '新疆', '新疆,', $area [0] );
					}elseif (strpos ( $area [0], '宁夏' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '宁夏', '宁夏,', $area [0] );
					}elseif (strpos ( $area [0], '西藏' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '西藏', '西藏,', $area [0] );
					}elseif (strpos ( $area [0], '内蒙古' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '内蒙古', '内蒙古,', $area [0] );
					}elseif (strpos ( $area [0], '省' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '省', '省,', $area [0] );
					}
					if (strpos ( $area [0], '地区' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '地区', '地区,', $area [0] );
					}elseif (strpos ( $area [0], '州市' ) === false && strpos ( $area [0], '州' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '州', '州,', $area [0] );
					}elseif (strpos ( $area [0], '市' ) !== false) {
						$ischina = true;
						$area [0] = str_replace ( '市', '市,', $area [0] );
					}
					if (strpos ( $area [0], '区' ) !== false) {
						$ischina = true;
					}
					if (strpos ( $area [0], '县' ) !== false) {
						$ischina = true;
					}
                    if (strpos ( $area [0], '旗' ) !== false) {
						$ischina = true;
					}
                    $area [0] = mb_substr ( $area [0], 0, mb_strrpos($area [0],','));
                    if($area [0]==='内蒙古' && strpos ( $area [1], '盟' ) !== false){
                        $area [0] = '内蒙古,'.strstr($area [1],'盟',true).'盟';
                        
                    }
					if ($ischina && strpos ( $area [0], '中国' ) === false) {
						$area [0] = '中国,' . $area [0];
					}
				}
				return $area;
			} else {
				return array ();
			}
		} catch ( Exception $ex ) {
			return array ();
		}
	
	}
	
	/**
	 * 用于需要过滤地区名称后面的市、区、县等字符的情况
	 * @param string $area_name 地区名称
	 * @param array $filter 过滤字符数组
	 */
	public static function filterAreaName($area_name='', array $filter=array('市')){
		$area_name=trim($area_name);
		if(count($filter)<1)
			return $area_name;
		$f=implode('|', $filter);
		$p="/(.*)[$f]$/u";
		return preg_replace($p, '$1', $area_name);
	}
	/**
	 * 设置缓存
	 * @param string    $modelname  模型名称
	 * @param string    $key        键值
	 * @param mix       $data       数据
	 * @param int       $expire     过期时间
	 */
	public static function setCache($modelname, $key, $data, $expire = 86400) {
		$modelname = strtolower ( $modelname );
		if (! isset ( Yii::app ()->params ['models'] [$modelname] )) {
			//return false;
			$modelname = 'default';
		}
		$id = Yii::app ()->params ['models'] [$modelname] ['cacheid'];
		if (Yii::app ()->getComponent ( $id )) {
			return Yii::app ()->$id->set ( $key, $data, $expire );
		}
		return false;
	}
	
	/**
	 * 获取缓存
	 * @param string    $modelname  模型名称
	 * @param string    $key        键值
	 * @param mix       $data       数据
	 * @param int       $expire     过期时间
	 */
	public static function getCache($modelname, $key) {
		$modelname = strtolower ( $modelname );
		if (! isset ( Yii::app ()->params ['models'] [$modelname] )) {
			//return false;
			$modelname = 'default';
		}
		
		$id = Yii::app ()->params ['models'] [$modelname] ['cacheid'];
		if (Yii::app ()->getComponent ( $id )) {
			return Yii::app ()->$id->get ( $key );
		}
		return false;
	}
	/**
	格式化数组为sql预处理格式
	 **/
	public static function toBindDataFormat(array $data, $flag = ':', $clearNullOrEmpty = true) {
		if (count ( $data )) {
			foreach ( $data as $key => $value ) {
				if ($clearNullOrEmpty === true) {
					$value = trim ( $value );
					if ($value === '' || strlen ( $value ) < 1 || $value === bull) {
						unset ( $data [$key] );
					}
				}
				$kkey = $flag . $key;
				$data ["$kkey"] = $value;
				unset ( $data [$key] );
			}
		}
	}
	/**
	 * 将id数组转化为SQL in 查询条件需要的字符
	 * @param array $idArray
	 */
	public static function toIdString(array $idArray=array()){
		$ids=array();
		foreach($idArray as $id){
			$ids[]=(int)$id;
		}
		$ids=array_unique($ids);
		$idStr=implode(',', $ids);
		return $idStr;
	}
	/**
	把一个汉字转化为带声调的拼音
	**/
	public static function toPinyin($zh,$to='UTF-8')
	{
		if( strlen($zh)===3 && mb_strlen($zh,'UTF-8')===1){
			$zh=mb_convert_encoding($zh,'GBK','UTF-8');
		}
		if (strlen($zh) != 2 && mb_strlen($zh,'GBK')!==1)
		{
			throw new Exception("`$zh` ls not chinese ");
		}
        $high = ord($zh[0]) - 0x81;
        $low  = ord($zh[1]) - 0x40;
        // 计算偏移位置
        $off = ($high<<8) + $low - ($high * 0x40);
		// 判断 off 值
		if ($off < 0)
		{
			throw new Exception("`$zh` ls not chinese");
		}
		$chinsespinyindata=UtilD::getCache('area','chinsespinyindata');
		if(!$chinsespinyindata){
			if(!file_exists('/home/www/py.dat') || !is_readable('/home/www/py.dat')){
				throw new Exception("unable to load PinYin data file `$pdat`");
			}
			$chinsespinyindata=file_get_contents('/home/www/py.dat');
			UtilD::setCache('area','chinsespinyindata',$chinsespinyindata);
		}
		$ret=substr($chinsespinyindata,$off * 8,8);
        $ret = unpack('a8py', $ret);
		if($to!=='GBK'){
			$ret['py']=mb_convert_encoding($ret['py'],'UTF-8','GBK');
		}
		$return =array('sd'=>0);
		$sd=substr($ret['py'],-1);
		if(is_numeric($sd)){
			$return['sd']=$sd;
			$return['py']=substr($ret['py'],0,-1);
		}else{
			$return['py']=$ret['py'];
		}
		return $return;
	}
	/**
	汉字转拼音
	 **/
	public static function cnToPinyin($str, $_Code = 'UTF-8') {
        if (!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $str)) {//不是中文
            return '';
        }
        if (mb_check_encoding($str, 'UTF-8')) {
            $str = mb_convert_encoding($str, 'GBK', 'UTF-8');
        }

        $len = mb_strlen($str, 'GBK');
        $ret = '';
        for ($i = 0; $i < $len; $i++) {

            try {
                $char = mb_substr($str, $i, 1, 'GBK');
                $xx = self::toPinyin($char);
            } catch (Exception $e) {
                $xx = array();
            }
            if (isset($xx['py'])) {
                $ret.=$xx['py'];
            } else {
                $ret.='unkown';
            }
        }
        return $ret;
    }
	
	/**
	 * 获取加后缀的文件
	 * @param string $filename
	 * @param string $extName
	 * @return string
	 */
	public static function getThumbFile($filename, $extName = '') {
		$filename=trim($filename);
		if($filename=='')
			return '';
		/* $filterDomain=array('img09.dld.com');
		foreach ($filterDomain as $server => $domain){
			if(strpos($filename, $domain)!==false){
				return $filename;
			}
		} */
		$pos = strrpos ( $filename, '.' );
		$ext = substr ( $filename, $pos );
		$allowExts = array ('.jpg', '.jpeg', '.gif', '.bmp', '.png' );
		if (! in_array ( strtolower($ext), $allowExts )) {
			return $filename;
		}
		$thumbFileName = substr ( $filename, 0, $pos ) . $extName . $ext;
		return $thumbFileName;
	}

    /**
     * 根据指定的键，使用其键值，对二维数组排序
     *
     * 用法：
     * @code php
     * $rows = array(
     *           array('id' => 1, 'value' => '1-1', 'parent' => 1),
     *           array('id' => 2, 'value' => '2-1', 'parent' => 1),
     *           array('id' => 3, 'value' => '3-1', 'parent' => 1),
     *           array('id' => 4, 'value' => '4-1', 'parent' => 2),
     *           array('id' => 5, 'value' => '5-1', 'parent' => 2),
     *           array('id' => 6, 'value' => '6-1', 'parent' => 3),
     * );
     *
     * $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
     * dump($rows);
     * // 输出结果为：
     * // array(
     * //         array('id' => 6, 'value' => '6-1', 'parent' => 3),
     * //         array('id' => 5, 'value' => '5-1', 'parent' => 2),
     * //         array('id' => 4, 'value' => '4-1', 'parent' => 2),
     * //         array('id' => 3, 'value' => '3-1', 'parent' => 1),
     * //         array('id' => 2, 'value' => '2-1', 'parent' => 1),
     * //         array('id' => 1, 'value' => '1-1', 'parent' => 1),
     * // )
     * @endcode
     *
     * @param array $array 要排序的数组
     * @param string $keyname 排序的键
     * @param int $dir 排序方向
     *
     * @return array 排序后的数组
     */
    public static function sortByCol($array, $keyname, $dir = SORT_ASC)
    {
        return self::sortByMultiCols($array, array($keyname => $dir));
    }
    /**
     * 将一个二维数组按照多个列进行排序，类似 SQL 语句中的 ORDER BY
     *
     * 用法：
     * @code php
     * $rows = Helper_Array::sortByMultiCols($rows, array(
     *           'parent' => SORT_ASC, 
     *           'name' => SORT_DESC,
     * ));
     * @endcode
     *
     * @param array $rowset 要排序的数组
     * @param array $args 排序的键
     *
     * @return array 排序后的数组
     */
    public static function sortByMultiCols($rowset, $args)
    {
        $sortArray = array();
        $sortRule = '';
        foreach ($args as $sortField => $sortDir) 
        {
            foreach ($rowset as $offset => $row) 
            {
                $sortArray[$sortField][$offset] = $row[$sortField];
            }
            $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
        }
        if (empty($sortArray) || empty($sortRule)) { return $rowset; }
        eval('array_multisort(' . $sortRule . '$rowset);');
        return $rowset;
    }
    
    /**
     * 将数值与进行&操作进行转换
     * @param integer $src 源数字
     * @param array $types 类型
    */
    public static function calcDigit($src,$types=array())
    {    
        $rlt = array();
    	foreach($types as $key=>$value){
    		if($src & $key){
    			$rlt[$key] = $value;
    		}
    	}
        return $rlt;
    }
	/**
	给图片打水印
	**/
	public static function waterPrint($image,$words='www.dld.com',$postation=array(0,60),$fontColor='#FFFFFF',$fontBoderColor='rgb(62,62,62)',$fontSzie=14){
		if(!file_exists($image)){
			return false;
		}
		$font=realpath(dirname(__FILE__) . '/acme.ttf');
		$command="/usr/local/imagemagick/bin/convert -quality 80 -font '{$font}' -stroke '{$fontBoderColor}' -fill '{$fontColor}' -gravity southEast -pointsize {$fontSzie} -draw 'text {$postation[0]},{$postation[1]} \"{$words}\"' {$image} {$image}";
		$string=shell_exec($command);
		if(empty($string)){
			return false;
		}
		return true;

	}
	/**
	 * 批量生成缩略图
	 * @param string $file 全路径  文件只能为本地文件，多张图片以回车分割
	 * @param string $size 全路径'60x60'
	 */
	public static function thumbPhotoFromFile($file,$size){
		//$command="#!/bin/bash\n";
		if(file_exists($file)){
			$contents=array();
			$contents=file($file);
			if(is_array($contents)){
				foreach($contents as $targetFile){
					$targetFile=trim($targetFile);
					$fs=pathinfo($targetFile);
					$ext=str_replace('.'.$fs['extension'], '_'.$size.'.'.$fs['extension'], $fs['basename']);
					$thumb=$fs['dirname'].DIRECTORY_SEPARATOR.$ext;
					/*
					if(strtolower($fs['extension']==='gif')){
						$fs['basename']=str_replace('.'.$fs['extension'],'.jpg', $fs['basename']);
						$gthumb=$fs['dirname'].DIRECTORY_SEPARATOR.$fs['basename'];
						shell_exec("/usr/local/imagemagick/bin/convert {$targetFile}[0] -background white -flatten -alpha off {$gthumb}");
						echo "/usr/local/imagemagick/bin/convert {$targetFile}[0] -background white -flatten -alpha off {$gthumb}";
						$targetFile=$gthumb;
						$fs=pathinfo($targetFile);
						$ext=str_replace('.'.$fs['extension'], '_'.$size.'.'.$fs['extension'], $fs['basename']);
						$thumb=$fs['dirname'].DIRECTORY_SEPARATOR.$ext;
					}*/
					$command="/usr/local/imagemagick/bin/convert  {$targetFile} -thumbnail '{$size}>' -gravity center -extent {$size} {$thumb}";
					shell_exec($command);
					
				}
			}
			
		}
	}

        
     /**
     * 短信发送
     * @param array    $phonex 手机号码
     * @param string    $msg 信息内容
     * @param int       $num 手机号码个数
     * @ref string      $ref 来源
     * @return string    $result false为发送失败 true为成功
     */
    public static function sendSMS($phonex, $msg, $num = 1, $ref = 'dld') {
    	$mode='999';
    	if($mode=='999'){
	    	/**
	    	 * 网关地址
	    	 */
	    	$gwUrl = 'http://sdk999ws.eucp.b2m.cn:8080/sdk/SDKService';
	    	
	    	/**
	    	 * 序列号,请通过亿美销售人员获取
	    	 */
	    	$serialNumber = '9SDK-EMY-0999-JCTNN';
	    	
	    	/**
	    	 * 密码,请通过亿美销售人员获取
	    	 */
	    	$password = '265418';
	    	$sessionKey = '123456';
    	}else{
	    	$gwUrl = 'http://sdk4report.eucp.b2m.cn:8080/sdk/SDKService?wsdl';
	    	$serialNumber = '6SDK-EMY-6688-JGSTR';
	    	$password = '148457';//148457
	    	$sessionKey = 'bc68d8259e8c5af';
    	}
    	/**
    	 * 登录后所持有的SESSION KEY，即可通过login方法时创建
    	 */
    	
    	
    	/**
    	 * 连接超时时间，单位为秒
    	 */
    	$connectTimeOut = 2;
    	
    	/**
    	 * 远程信息读取超时时间，单位为秒
    	 */
    	$readTimeOut = 10;
    	
    	/**
    	 * $proxyhost		可选，代理服务器地址，默认为 false ,则不使用代理服务器
    	 * $proxyport		可选，代理服务器端口，默认为 false
    	 * $proxyusername	可选，代理服务器用户名，默认为 false
    	 * $proxypassword	可选，代理服务器密码，默认为 false
    	 */
    	$proxyhost = false;
    	$proxyport = false;
    	$proxyusername = false;
    	$proxypassword = false;
    	$client = new MobileApi ( $gwUrl, $serialNumber, $password, $sessionKey, $proxyhost, $proxyport, $proxyusername, $proxypassword, $connectTimeOut, $readTimeOut );
    	/* $statusCode = $client->login ();
    	if (! ($statusCode != null && $statusCode == "0")) {

    		return false;//登录失败
    	} */
    	$mobiles=is_array($phonex)?$phonex:array(trim($phonex));
    	$rs=$client->sendSMS ( $mobiles, $msg );
    	//记录短信发送日志以便查询
		if($rs == 0){
	    	$log = new UserSmsSendlog();
	    	$log->addSmsSendlog($phonex,$msg,$num,$ref);
	    	return '100';
		}else{
			Yii::log('接口发送短信失败，返回值 :'.$rs, 'error', 'system.*');
			return false;
		}
		//return true;//节省短信，暂时不发
		/*
        define('SMS_USER', 'J00680');
        define('SMS_PASS', '680223');
        if (empty($phonex))
            return false;
		if(is_array($phonex)){
            $phonex=implode($phonex,';');
		}
		else{
            $phonex = trim($phonex);
		}
        $url = 'http://ws.montnets.com:9002/MWGate/wmgw.asmx/MongateCsSpSendSmsNew' . '?userId=' . SMS_USER . '&password=' . SMS_PASS . '&pszMobis=' . $phonex . '&pszMsg=' . urlencode($msg) . '&iMobiCount=' . $num . '&pszSubPort=1'; 
        ////iMobiCount 手机号码个数 pszSubPort端口号 1
        $content = file_get_contents($url);
        if (!preg_match("/>([\-|0-9]+)</", $content, $res)) {
            return false;
        }
        if (strlen($res [1]) <= 10 || strlen($res [1]) >= 25) {
            return false;
        }
        return '100';
        */
        /*if( mb_check_encoding($msg,'UTF-8')){
        	$msg=mb_convert_encoding($msg,'GBK','UTF-8');
        }
        $pwd=urlencode('abc123');
        $msg=urlencode(base64_encode($msg));
		if(is_array($phonex)){
            $c=implode($phonex,';');
		}
		else{
            $c=$phonex;
		}
        $http=new HttpClientD("http://219.133.59.215:8686/http/httpserver2?enterpriseid=432194&pswd={$pwd}&mobs={$c}&msg={$msg}&comid=101");
        $http->open();
        return $http->excute();*/ 

    }
	/**
	 时间差取整 获得指定时间一小时内或一分钟内的起始时间戳
	* @param string    $format 仅仅为 minute 或者 hour
	* @param int   ,$compareTime 要比较的unix时间戳 为0则默认为服务器当前时间
	**/
	public static function ceilTime($unit='minute',$compareTime=0){
		if($compareTime===0){
			$compareTime=$_SERVER['REQUEST_TIME'];
		}
		$hours=date('H',$compareTime);
		$minutes=date('i',$compareTime);
		$months=date('m',$compareTime);
		$days=date('d',$compareTime);
		$years=date('Y',$compareTime);
		return $unit==='hour'?mktime((int)$hours,0,0,(int)$months,(int)$days,(int)$years):mktime((int)$hours,(int)$minutes,0,(int)$months,(int)$days,(int)$years);
	}
    
    
    /**
     * 在页面操作完之后生成JavaScript的提示和页面跳转
     * @param string    $message        alert的提示文字
     * @param string    $url            可选参数，需要跳转的URL地址
     * @param string    $level          可选参数，top,parent用于iframe内部页面的跳转控制
     * @author dcl 2012-02-27
     * @example 调用 UtilD::toJavaScriptAlert("提交成功", "?r=admin/shop/index");
     * @example 输出 <script>parent.alert("提交成功");parent.location.href='?r=admin/shop/index';</script>
     * @example 输出后自动 Yii::app()->end();
     */
    public static function toJavaScriptAlert($message, $url = '', $level = 'parent' ){
        $iframe = ($level == '') ? '' : $level .".";
        $result  = "<script type='text/javascript'>" . $iframe . "alert('" . $message . "');";
        if ($url != '' && $url != 'back'){
        	if(substr($url, 0,4) == 'http' || substr($url, 0,1) == '/'){
        		//如果url为网址则直接跳转到网址，否则跳到来源页
        	}else{
        		$page_referer = self::deSlashes(Yii::app()->request->getPost("PAGE_REFERER", ""));
        		if ($page_referer != ''){//如果视图页面有指定的跳转页面，优先使用跳转，没有则使用控制器指定的默认页面
        			$url = $page_referer;
        		}
        	}
          
            $result .= $iframe . "location.href='" . $url . "';";
        }
        elseif ($url =='back') {
        	$result .="history.back();";
        }
        $result  .= "</script>";
        echo $result;
        Yii::app()->end();
    }

    /*
	*把不安全的的标签转化为实体,如<script </script>,可以根据需求扩展
	*/
	public static function enSlashUnsafeTag($string){
		//不安全标签转换数组，可以根据需求扩展
		$replaces = array(
			            '<script' => '&ltscript',
			            '</script>' => '&lt/script&gt',
			            '<style' => '&ltstyle',
			            '</style>' => '&lt/style&gt',
		            );
		if(!empty($string)){
            $string = strtr($string,$replaces);
		} 

		return $string;
	}
	/**
	 * 过滤不完整的utf8编码字符
	 * @param string $str
	 * @return string
	 */
	public static function filterPartialUTF8Char($str){
		$str = preg_replace("/[\\xC0-\\xDF](?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
		$str = preg_replace("/[\\xE0-\\xEF][\\x80-\\xBF]{0,1}(?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
		$str = preg_replace("/[\\xF0-\\xF7][\\x80-\\xBF]{0,2}(?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
		return $str;
	}
	/**
	 * @desc 适用于中文字符的搜索和替换
	 * @return string
	 * @access public
	 * @author linjing
	 */	
	function mb_str_replace($search, $replace, $subject) {
	
		if(is_array($subject)) {
			$ret = array();
			foreach($subject as $key => $val) {
				$ret[$key] = mb_str_replace($search, $replace, $val);
			}
			return $ret;
		}
	
		foreach((array) $search as $key => $s) {
			if($s == '') {
				continue;
			}
			$r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
			$pos = mb_strpos($subject, $s);
			while($pos !== false) {
				$subject = mb_substr($subject, 0, $pos) . $r . mb_substr($subject, $pos + mb_strlen($s));
				$pos = mb_strpos($subject, $s, $pos + mb_strlen($r));
			}
		}
	
		return $subject;
	
	}
	/**
	 * @desc 还原被过滤的内容
	 * @return string
	 * @access public
	 * @author linjing
	 */	
	function revertFilterWord($content=''){
		$pattern = '/\"words_fiter\">(.*?)<\/div>/';
		if($content == ''){
			return $content;
		}
		
		if(strpos($content,'words_fiter')!=false){
			preg_match_all($pattern,UtilD::deSlashes($content),$arr);
			$find_word = array_values($arr['1']);
			foreach($arr['1'] as $k=> $v) {
				$arr[$k] = base64_decode($v);
			}
			$content = str_replace($find_word,$arr,UtilD::deSlashes($content)); 
			$content = str_replace('<div style="display:none" class="words_fiter">','',$content);
			$content = str_replace('</div>','',$content);
		
		}
		return $content;
	}
	/**
	 * 计算两点GPS坐标的距离
	 * @param number $n1 第一点的纬度坐标
	 * @param number $e1 第一点的经度坐标
	 * @param number $n2 第二点的纬度坐标
	 * @param number $e2 第二点的经度坐标
	 */
	public static function GPSDistance($n1, $e1, $n2, $e2){
		$jl_jd = 102834.74258026089786013677476285;
		$jl_wd = 111712.69150641055729984301412873;
		$b = abs(($e1 - $e2) * $jl_jd);
		$a = abs(($n1 - $n2) * $jl_wd);
		$l=sqrt(($a * $a + $b * $b));
		return $l;
	}
	
	/**
	 * 快速排序
	 * @param unknown_type $array
	 * @return unknown|multitype:
	 */
    public static function quicksort($array) {
        $count = count ( $array );
        if ($count <= 1)
            return $array;
        $key = $array [0];
        $left_array = array ();
        $middle_array = array ();
        $right_array = array ();
       
        foreach ( $array as $each ) {
            if ($key > $each) {
                //入栈
                array_push ( $left_array, $each );
            } else if ($key == $each) {
                //直接插入
                $middle_array [] = $each;
            } else {
                $right_array [] = $each;
            }
        }
        $left_array = self::quicksort ( $left_array );
        $right_array = self::quicksort ( $right_array );
        $array = array_merge ( $left_array, $middle_array, $right_array );
        return $array;
    }
    
    /**
     * 判断页面的模块数据是否启用状态
     * @param string	$area_code
     * @param string	$alias
     * @return boolean
     * */
    public static function isPageSetup($area_code, $alias){
    	$data = PageModule::getMemInfoByAlias($alias);
    	if (is_null($data) || $data['sta'] == 0){
    		return false;
    	}
    	$siteInfo = SiteConfig::getSiteInfoByAreaCode($area_code);
    	if (is_null($siteInfo)){
    		return $data['default_sta'] == 1 ? true : false;
    	}
    	$criteria = new CDbCriteria();
    	$criteria->addCondition(" site_id = {$siteInfo['id']} AND module_id = {$data['id']} ");
    	$siteItem = SiteToModule::model()->getListByPage(1, 1, $criteria);
    	if ($siteItem['count'] == 0){//如果没有自定义配置，则使用默认配置
    		return $data['default_sta'] == 1 ? true : false;
    	}else{
    		return (isset($siteItem['data'][0]['sta']) && $siteItem['data'][0]['sta']) == 1 ? true : false;
    	}
    	return true;
    }
    /**
     * 去掉HTML标签
     * @param unknown_type $str
     * @return mixed
     */
    public static function delhtml($str){   //清除HTML标签
    	$st=-1; //开始
    	$et=-1; //结束
    	$stmp=array();
    	$stmp[]="&nbsp;";
    	$len=strlen($str);
    	for($i=0;$i<$len;$i++){
    		$ss=substr($str,$i,1);
    		if(ord($ss)==60){ //ord("<")==60
    			$st=$i;
    		}
    		if(ord($ss)==62){ //ord(">")==62
    			$et=$i;
    			if($st!=-1){
    				$stmp[]=substr($str,$st,$et-$st+1);
    			}
    		}
    	}
    	$str=str_replace($stmp,"",$str);
    	return $str;
    }
    
    /*
     * 将数据格式化成WAP需要的格式（去掉HTML标签和空格）
     */
    function fomat_wap_data($text){
       $text = strip_tags(UtilD::deSlashes($text));
       $text = str_replace('&nbsp;','',$text);
       $text = str_replace('　','',$text);
       return $text;
    }
    
    /*
     * 将电话号码转换成在wap网页中可以拨打的格式
    */
    function to_wap_tel($tel){
    	$t = '';
    	$tels = strip_tags(UtilD::deSlashes($tel));
    	$tels = explode(' ',$tels);
    	if(is_array($tels)){
    		foreach($tels as $k => $v){
    			if(!empty($v)){    				
    				$t .= $v.'<a href="wtai://wp/mc;'.str_replace('-', '', $v).'">[拨打]</a> ';
    			}
    		}
    	}

    	return $t;
    }
    
    /*
     * 生成快捷方式
     * $url 快捷方式指向的网址
     * $name 快捷方式名称
     *
     */
    public static function createQuickLink($name,$url) {
    	$name = iconv("utf-8","gb2312",$name);
    	$link = "
 [InternetShortcut]
URL={$url}
IDList=
IconFile=http://www.dld.com/favicon.ico
IconIndex=1
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
"; 
    	Header("Content-type: application/octet-stream");
    	header("Content-Disposition: attachment; filename=".$name.".url;");
    	
    	
    	echo $link;
    	Yii::app()->end();    	
    }
   
    public static function isMobileRequest($agent=null){
    	$flag = false;
    	is_null($agent) && $agent = isset($_SERVER ['HTTP_USER_AGENT'])?$_SERVER ['HTTP_USER_AGENT']:'';
    	$pattern = '/(iphone|android|mini|mobile|mobi|nokia|symbian|ipod|windows phone|mqqbrowser|wp7|ucbrowser7|ucweb|samsung|midp-2|symbianos|untrusted\/1.0|windows ce|blackberry|brew|j2me|yulong|coolpad|tianyu|ty-|k-touch|haier|dopod|lenovo|huaqin|aigo-|ctc\/1.0|ctc\/2.0|cmcc|daxian|mot-|sonyericsson|gionee|htc|zte|huawei|webos|gobrowser|iemobile|wap2.0)/i';
    	$pattern2 = '/ipad/i';//排除ipad, 由于agent信息中可能同时含有ipad和mobile信息
    	if (preg_match ( $pattern, $agent ) && !preg_match ( $pattern2, $agent )) {
    		$flag = true;
    	}
    	return $flag;
    }
    
   	/**
   	 * 查询本地库，如果有手机号短地址信息，就直接读取，否则调用第三方接口
   	 * params $mobile_number 手机号
   	 * return  $area_name 返回地名
   	 * author：panxb
   	 * 
   	 * */
    
    public  static  function getMobileInfo($mobile){ 
    	$msg = array('key'=>0,'keyMain'=>'暂无信息');
    	try{
	    	/* 先查本地库*/
	    	$area_info = new MobileData();
    		$area_data = $area_info->getMobileInfo($mobile);
    		if($area_data){
    			$msg = array('key'=>1,'keyMain'=>$area_data);
    		}else{
		    /*如果本地库没在查看相关信息，查询第三方接口,并把相关手机号段写入本地号码地址库*/
    			/*
	    		$url = 'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo';
	    		$httpClient = new HttpClientD($url);
	    		$httpClient->open();
	    		$httpClient->setPostData(array('mobileCode'=>$mobile,'userId'=>''));
	    		$data = $httpClient->excute();
	    		$data = simplexml_load_string($data);
	    		if(strpos($data, 'http://')){
	    			$msg = array('key'=>-1,'keyMain'=>'手机号码格式错误');
	    		}elseif(!preg_match('/\d{7,12}/', $data)){
	    			$msg = array('key'=>-1,'keyMain'=>'手机号码格式不匹配');
	    		}else{
	    			$data = explode(' ',substr_replace($data,'',0, strlen( $mobile."：")));
	    			if(count($data)==3){
	    				$link_data = $data[0].' '.$data[1];
	    				$mobile_info= new MobileData();
	    				$mobile_info->saveItem($mobile,$link_data,$data[2]);
	    				$msg = array('key'=>   1,'keyMain'=>$link_data);
	    			}else{
	    				$msg = array('key'=>-1,'keyMain'=>'地区信息不完善');
	    			}
	    		}*/
    			$msg = self::getAreaByMobile($mobile);
    		}
    	}catch (Exception $e){
    		$msg = array('key'=>0,'keyMain'=>'异常错误');
    	}
    	return $msg;
    }
    
    
    public static function getAreaByMobile($mobile){
    			$msg = array('key'=>0,'keyMain'=>'暂无相关信息');
    			$url = 'http://wap.ip138.com/sim_search.asp?mobile='.$mobile;
    			$httpClient = new HttpClientD($url);
    			$httpClient->open();
    			$data = $httpClient->excute();
    			preg_match('/<div>手机号：(\d.+)<br\/>\s*归属地：(.*)<br\/>\s*卡类型：(.*)<br\/>/', $data,$matchies);
    			if(!empty($matchies)){
    				$mobile_info= new MobileData();
    				$mobile_info->saveItem($mobile,$matchies[2],$matchies[3]);
    				$msg = array('key'=>1,'keyMain'=>$matchies[2]);
    			}else{
    				$msg = array('key'=>-1,'keyMain'=>'该号码不存在或暂无相关地区信息！');
    			}
    	return $msg;
    }
    
    public static function dateToEndDatetime($date){
    	if(!empty($date)){
    		return $date.' 23:59:59';
    	}
    	return $date;
    }
    
    /**
     * 随机生成团购劵号
     */
    public static function random_num($length = 12)
    {
    	$length = (int)$length;
    	$loops = ceil($length / 3);
    	$string = '';
    	for ( $i=0; $i<$loops; $i++ )
    	{
    		$string .= (string)mt_rand(100, 999);
    	}
    	$string = substr($string, 0, $length);
    	return $string;
    }
    
    /*
     * 随机生成
     * */
    public static function random($length=8, $idtype='ALL') {
    	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    	$hash = '';
    	for ($i = 0; $i < $length;  $i++) {
    		if ( 'NUM' == $idtype ) {
    			if (0==$i) {
    				$hash .= chr(rand(49, 57));
    			} else {
    				$hash .= chr(rand(48, 57));
    			}
    		} else if ( 'WORD' == $idtype ){
    			$hash .= chr(rand(65, 90));
    		} else {
    			if ( 0==$i ) {
    				$hash .= chr(rand(65, 90));
    			} else {
    				$hash .= (0==rand(0,1))?chr(rand(65, 90)):chr(rand(48,57));
    			}
    		}
    	}
    	return $hash;
    }
    
    /*
     * 获取指定$url的html代码
    */
    public static function get_url($url){
    	/*if (!$fp = fopen($url, "r")) return '';
    	$content = '';
    	while($fc = fread($fp, 8192)){
    		$content .= $fc;
    	}
    	fclose($fp);*/
    	$content = file_get_contents($url);
    	if (empty($content)) return '';
    	if (preg_match('/404\s+Error/i', $content)) return '';
    	//匹配主体内容
    	preg_match('/<head>.*<\/body>/ism', $content,$out);
    	return isset($out[0])?$out[0]:'';
    }
}
?>
